package com.jingli.pile.util;

import org.apache.commons.lang3.StringUtils;

import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
public class HMacMd5KeyFactory extends KeyFactorySpi{
    @Override
    protected PublicKey engineGeneratePublic(KeySpec keySpec) throws InvalidKeySpecException {
        if(keySpec instanceof  HMacMd5KeySpec) {
            return new HMacMd5Key((HMacMd5KeySpec) keySpec);
        }
        throw new InvalidKeySpecException("只支持HMacMd5KeySpec");
    }

    @Override
    protected PrivateKey engineGeneratePrivate(KeySpec keySpec) throws InvalidKeySpecException {
        if(keySpec instanceof  HMacMd5KeySpec) {
            return new HMacMd5Key((HMacMd5KeySpec) keySpec);
        }
        throw new InvalidKeySpecException("只支持HMacMd5KeySpec");
    }

    @Override
    @SuppressWarnings({"unchecked","cast"})
    protected <T extends KeySpec> T engineGetKeySpec(Key key, Class<T> keySpec) throws InvalidKeySpecException {
        if(StringUtils.equals(keySpec.getClass().getName(), HMacMd5KeySpec.class.getName())){
            return (T)new HMacMd5KeySpec(key.getEncoded());
        }
        throw new InvalidKeySpecException("只支持HMacMd5KeySpec");
    }

    @Override
    protected Key engineTranslateKey(Key key) throws InvalidKeyException {
        byte[] keyData = key.getEncoded();
        return new HMacMd5Key(new HMacMd5KeySpec(keyData));
    }
}
